package edu.njucm.herbiv.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.njucm.herbiv.pojo.entity.AnalysisOrder;
import edu.njucm.herbiv.service.HerbivService;
import edu.njucm.herbiv.utils.ErrorUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @Author ZhouHang
 * @Date 24/4/25 025
 */
@RestController
@RequestMapping("/api/herbiv")
@CrossOrigin(origins = "*")
public class HerbivController {
    @Resource
    private HerbivService herbivService;
    private final Logger logger = LoggerFactory.getLogger(HerbivController.class);

    @PostMapping("/from_tcm")
    @SuppressWarnings("unchecked")
    public Map<String, Object> fromTcm(@RequestBody Map<String, Object> req) {
        Object tcms = req.get("tcms");
        if (tcms == null) {
            return ErrorUtils.constructMessage(3000, "参数传递错误");
        }
        List<String> tcmsList = (List<String>) tcms;

        Timestamp now = new Timestamp(System.currentTimeMillis());
        String encodeStr = String.join(",", tcmsList) + now;
        String analysisNo = DigestUtils.md5DigestAsHex(encodeStr.getBytes(StandardCharsets.UTF_8));
        CompletableFuture<String> stringCompletableFuture = herbivService.fromTcm(tcmsList, now, analysisNo);
        stringCompletableFuture.thenAccept(logger::warn);
        logger.info(encodeStr);
        return ErrorUtils.constructMessage(2000, "Success", "analysis_no", analysisNo);
    }

    /**
     * 获得某 id 分析对应的结果
     * @param analysisNo 订单号
     * */
    @PostMapping("/get_result")
    @SuppressWarnings("unchecked")
    public Map<String, Object> getResult(@RequestParam("analysis_no") String analysisNo) {
        AnalysisOrder analysisOrder = herbivService.getResult(analysisNo);
        if (analysisOrder == null) {
            return ErrorUtils.constructMessage(3000, "请输入正确的分析号");
        }
        if (analysisOrder.getStatus() == 0) {
            // 正在分析中
            return ErrorUtils.constructMessage(2001, "正在分析中，请稍后再尝试");
        } else if (analysisOrder.getStatus() == -1) {
            // 分析失败
            return ErrorUtils.constructMessage(3000, "分析失败");
        } else {
            // 分析成功，返回数据
            String result = analysisOrder.getResults();
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> resultMap = objectMapper.readValue(result, Map.class);
                Map<String, Object> ret = new HashMap<>();
                ret.put("code", 2000);
                ret.put("result", resultMap);
                ret.put("input_ids", analysisOrder.getInputIds());
                ret.put("create_time", analysisOrder.getCreateTime().toString());
                return ret;
            } catch (JsonProcessingException e) {
                return ErrorUtils.constructMessage(4000, "JSON 解析错误");
            } catch (NoSuchMethodError e) {
                return ErrorUtils.constructMessage(4001, "JSON 解析错误（不存在方法）");
            }
        }
    }

    @PostMapping("/get_chart")
    public String getChart(@RequestParam("analysis_no") String analysisNo) {
        return herbivService.getChart(analysisNo);
    }

}
